package cool.taomu.toolkit.service.client.kademlia

import com.google.auto.service.AutoService
import com.google.inject.AbstractModule
import com.google.inject.Key
import com.google.inject.name.Names
import cool.taomu.toolkit.TaomuConfigure
import cool.taomu.toolkit.platform.inter.AbsPlatform
import cool.taomu.toolkit.platform.inter.IPlatform
import cool.taomu.toolkit.service.client.kademlia.module.ServiceClientModule
import cool.taomu.toolkit.service.client.kademlia.utils.ClientExec
import cool.taomu.toolkit.service.kademlia.entity.KPeerNode
import cool.taomu.toolkit.service.kademlia.service.ICheckPeer
import org.slf4j.LoggerFactory

@AutoService(IPlatform)
class ServiceClientPlugin extends AbsPlatform {
    val static LOG = LoggerFactory.getLogger(ServiceClientPlugin);

    override note() {
        "服务客户端插件"
    }

    override packages() {
    }

    override module(TaomuConfigure configure) {
        new AbstractModule() {
            override configure() {
                LOG.info("加载 service client 配置")
                install(new ServiceClientModule)
            	bind(ClientExec)
            }
        }
    }

    override start() {
    }

    override init() {
        val injector = this.context.injectorSupplier.get
        val gkeyHost = Key.get(String, Names.named("taomu.kademlia.peer.host"));
        val gkeyPort = Key.get(Integer, Names.named("taomu.kademlia.peer.port"));
        if (injector.getExistingBinding(gkeyHost) !== null) {
            this.context.executor.execute([
                // 加入节点
                var checkPeer = injector.getInstance(ICheckPeer)
                var host = injector.getInstance(gkeyHost)
                var port = injector.getInstance(gkeyPort)
                var peer = new KPeerNode(host, port);
                var check = checkPeer.apply(peer);
                LOG.info("建立连接:{}", check)
            ])
        }
    }
}
